package com.niodata.md.rdb.crawler;

import com.niodata.md.rdb.model.Index;
import com.niodata.md.rdb.model.Table;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * retrieve index metadata from the target table.
 */
public class IndexRetrieval extends AbstractRetrieval {
  @Override
  public List<MetaDataRetrieval> retrieveMetaData() throws Exception {
    Table table = this.getCatalog().getTable(this.getParentPath());
    ResultSet rs = this.getMetaData().getIndexInfo(table.getCatalog(),
        table.getSchema(), table.getName(),
        false, false);
    List<Index> indices = new ArrayList<>();
    while (rs.next()) {
      Index index = new Index();
      indices.add(index);
      index.setCatalog(table.getCatalog());
      index.setDatabase(table.getDatabase());
      index.setSchema(table.getSchema());
      index.setTable(table.getName());
      index.setName(rs.getString("INDEX_NAME"));
      index.setColumn(rs.getString("COLUMN_NAME"));
      index.setOrdinal(rs.getInt("ORDINAL_POSITION"));
      index.setNonUnique(rs.getBoolean("NON_UNIQUE"));
      index.setType(rs.getString("TYPE"));
    }
    table.setIndexSize(indices.size());
    table.setIndices(indices);
    return Collections.emptyList();
  }
}
